#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主应用文件
AI测试自动化平台 - Flask后端服务
"""

import os
from app_factory import create_app
from config import current_config
from database.mysql_manager import mysql_manager

# 创建应用实例
app = create_app()

# 初始化数据库索引
with app.app_context():
    mysql_manager.create_indexes()

# 向后兼容的路由支持
@app.route('/api/login', methods=['POST'])
def legacy_login():
    """向后兼容的登录接口"""
    from flask import request
    from controllers.auth_controller import get_auth_service
    from utils.validators import validate_login_data
    from utils.response_helper import success_response, error_response
    
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 验证数据
        validation_result = validate_login_data(data)
        if not validation_result['valid']:
            return error_response(validation_result['message'], 400)
        
        # 认证用户
        auth_service = get_auth_service()
        result = auth_service.authenticate_user(
            data.get('username'),
            data.get('password')
        )
        
        if result['success']:
            return success_response(
                data=result['user'],
                message=result['message']
            )
        else:
            return error_response(result['message'], 401)
            
    except Exception as e:
        return error_response(f'Login error: {str(e)}', 500)

@app.route('/api/register', methods=['POST'])
def legacy_register():
    """向后兼容的注册接口"""
    from flask import redirect, url_for
    return redirect(url_for('auth.register'))

@app.route('/api/users', methods=['GET'])
def legacy_users():
    """向后兼容的用户列表接口"""
    from flask import redirect, url_for
    return redirect(url_for('auth.get_users'))

@app.route('/api/user/<user_id>', methods=['GET'])
def legacy_user(user_id):
    """向后兼容的用户详情接口"""
    from flask import redirect, url_for
    return redirect(url_for('auth.get_user', user_id=user_id))

@app.route('/api/project', methods=['POST'])
def legacy_create_project():
    """向后兼容的创建项目接口"""
    from flask import redirect, url_for
    return redirect(url_for('project.create_project'))

if __name__ == '__main__':
    print(f"启动 {current_config.APP_NAME} v{current_config.APP_VERSION}")
    print(f"MySQL URI: {current_config.MYSQL_URI}")
    print(f"数据库: {current_config.MYSQL_DB}")
    gray_mode_text = "开启" if current_config.GRAY_MODE else "关闭"
    print(f"灰度模式: {gray_mode_text}")
    
    app.run(
        debug=current_config.DEBUG, 
        host=current_config.HOST, 
        port=current_config.PORT
    )